package org.dizem.minichat.service;

import org.apache.log4j.Logger;
import org.dizem.minichat.model.Server;
import org.dizem.minichat.util.VOUtil;
import org.dizem.minichat.vo.DataPacket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * User: DIZEM
 * Time: 11-3-26 上午9:40
 */
public class ServerMonitor extends Thread {

	private Logger log = Logger.getLogger(ServerMonitor.class);

	private Server server;
	public static final int SERVER_PORT = 9999;

	public ServerMonitor(Server server) {
		this.server = server;
	}

	@Override
	public void run() {
		try {
			DatagramSocket ds = new DatagramSocket(SERVER_PORT);
			while (true) {
				log.info("ServerMonitor is running");

				byte[] data = new byte[10000];
				DatagramPacket packet = new DatagramPacket(data, data.length);
				ds.receive(packet);

				String jsonString = new String(packet.getData(), 0, packet.getLength(), "UTF-8");
				log.info("Received : " + jsonString);

				DataPacket dp = (DataPacket) VOUtil.convertString2VO(jsonString, DataPacket.class);
				log.info("Convert string into DataPacket [operation = " + dp.getOperation() + "]");

				dealOperation(dp);
//				if (gp.getOperation().equals("Connect")) {
//					String clientAddress = packet.getAddress().getHostAddress();
//					int clientPort = gp.getClientPort();
//					server.connect(gp.getPlayerName(), clientAddress, clientPort);
//				} else if (gp.getOperation().equals("notifyPlayerInfoUpdate")) {
//					server.notifyPlayerInfoUpdate(gp.getPlayerId(), gp.getPlayerVO());
//				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	private void dealOperation(DataPacket dp) {
		switch (dp.getOperation()) {
			case REGISTER:

				break;

			case LOGIN:
				break;

			case RECEIVED_SUCCESS:
				break;
		}
	}
}
